<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>EggJs | 北城韩雨</title><meta name="keywords" content="Egg"><meta name="author" content="北城韩雨"><meta name="copyright" content="北城韩雨"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="Egg">
<meta property="og:type" content="article">
<meta property="og:title" content="EggJs">
<meta property="og:url" content="http://example.com/2020/03/22/egg/index.html">
<meta property="og:site_name" content="北城韩雨">
<meta property="og:description" content="Egg">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcz-video-photo.oss-cn-beijing.aliyuncs.com%2F20191017%2F4cfc341591d242327b67e9ceb6953612_00002.jpg&refer=http%3A%2F%2Fcz-video-photo.oss-cn-beijing.aliyuncs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629530702&t=80943e12d5239f63beafd6d1c540855f">
<meta property="article:published_time" content="2020-03-21T16:00:00.000Z">
<meta property="article:modified_time" content="2019-06-02T16:00:00.000Z">
<meta property="article:author" content="北城韩雨">
<meta property="article:tag" content="Egg">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcz-video-photo.oss-cn-beijing.aliyuncs.com%2F20191017%2F4cfc341591d242327b67e9ceb6953612_00002.jpg&refer=http%3A%2F%2Fcz-video-photo.oss-cn-beijing.aliyuncs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629530702&t=80943e12d5239f63beafd6d1c540855f"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2020/03/22/egg/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'mediumZoom',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'EggJs',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2019-06-03 00:00:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/custom.css"  media="defer" onload="this.media='all'"><link rel="stylesheet" href="/css/coin.css"  media="defer" onload="this.media='all'"><link rel="stylesheet" href="/css/liuxing.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/l-lin/font-awesome-animation/dist/font-awesome-animation.min.css"  media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/zhheo/JS-Heo@main/bb/showbb_in_index.css"><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" media="print" onload="this.media='screen'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/l-lin/font-awesome-animation/dist/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-butterfly-tag-plugins-plus/lib/tag_plugins.min.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.3.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/my.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">65</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">23</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">21</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><i class="fa-fw fas fa-home faa-tada"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/shuoshuo/"><i class="fa-fw fas fa-archive faa-tada"></i><span> 叨逼叨</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/tags/"><i class="fa-fw fas fa-tags faa-tada"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/categories/"><i class="fa-fw fas fa-folder-open faa-tada"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/link/"><i class="fa-fw fas fa-link faa-tada"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/comments/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-message"></use></svg><span> 留言板</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/about/"><i class="fa-fw fas fa-heart faa-tada"></i><span> 个人简介</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcz-video-photo.oss-cn-beijing.aliyuncs.com%2F20191017%2F4cfc341591d242327b67e9ceb6953612_00002.jpg&amp;refer=http%3A%2F%2Fcz-video-photo.oss-cn-beijing.aliyuncs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530702&amp;t=80943e12d5239f63beafd6d1c540855f')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">北城韩雨</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><i class="fa-fw fas fa-home faa-tada"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/shuoshuo/"><i class="fa-fw fas fa-archive faa-tada"></i><span> 叨逼叨</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/tags/"><i class="fa-fw fas fa-tags faa-tada"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/categories/"><i class="fa-fw fas fa-folder-open faa-tada"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/link/"><i class="fa-fw fas fa-link faa-tada"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/comments/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-message"></use></svg><span> 留言板</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/about/"><i class="fa-fw fas fa-heart faa-tada"></i><span> 个人简介</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">EggJs</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-03-21T16:00:00.000Z" title="发表于 2020-03-22 00:00:00">2020-03-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2019-06-02T16:00:00.000Z" title="更新于 2019-06-03 00:00:00">2019-06-03</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Node/">Node</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>9分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="EggJs"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="1-egg-js-项目初始化"><a href="#1-egg-js-项目初始化" class="headerlink" title="1.egg.js 项目初始化"></a>1.egg.js 项目初始化</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>创建命令</span><br><span class="line">npm init egg --type=simple 初始化项目</span><br><span class="line">npm i 安装egg</span><br><span class="line"><span class="number">2.</span>启动命令 </span><br><span class="line">进去项目文件夹下</span><br><span class="line">yarn run dev</span><br></pre></td></tr></table></figure>
<h1 id="2-项目目录结构"><a href="#2-项目目录结构" class="headerlink" title="2.项目目录结构"></a>2.项目目录结构</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>app 文件夹 用于存放我们的主要业务代码 比如我们的controller层的代码 router.js路由文件 model 数据层 middlerware中间层文件 </span><br><span class="line">在这里所有的文件的<span class="built_in">this</span>就是app 我们都可以通过把<span class="built_in">this</span>结构出来 然后通过ctx.model(文件夹).文件 这种方式 拿到里面的方法</span><br><span class="line"><span class="number">2.</span>config文件 里面有config.default.js文件 和 plugin.js文件 </span><br><span class="line"> config.default.js 主要用于配置我们的插件 比如mongoose 和 jwt </span><br><span class="line"> plugin.js 插件 主要用于加载我们的 mongoose 和 jwt 插件 </span><br><span class="line"> 我们所有的插件都必须在plugin.js里加载一下 然后在去 config.default.js里去配置一下</span><br><span class="line"><span class="number">3.</span>以上是我们项目命令搭建以后自动会产生的文件夹</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">4.</span>app文件夹下的 service 文件夹 我们新建的 一般用于存放公共的方法 在任何地方都可以调用</span><br><span class="line"><span class="comment">//service 文件夹 下user.js 文件  切记最后一定要导出</span></span><br><span class="line"><span class="meta">&#x27;use strict&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> Service = <span class="built_in">require</span>(<span class="string">&#x27;egg&#x27;</span>).Service;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserService</span> <span class="keyword">extends</span> <span class="title">Service</span> </span>&#123;</span><br><span class="line">  <span class="keyword">async</span> <span class="function"><span class="title">getAll</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> [&#123; <span class="attr">name</span>: <span class="string">&#x27;zs&#x27;</span> &#125;];</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">module</span>.exports = UserService;</span><br><span class="line"><span class="comment">//然后我们在app文件夹下 的controller文件夹下的文件就可以调用</span></span><br><span class="line"><span class="meta">&#x27;use strict&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> Controller = <span class="built_in">require</span>(<span class="string">&#x27;egg&#x27;</span>).Controller;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HomeController</span> <span class="keyword">extends</span> <span class="title">Controller</span> </span>&#123;</span><br><span class="line">  <span class="keyword">async</span> <span class="function"><span class="title">index</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; ctx &#125; = <span class="built_in">this</span>;</span><br><span class="line">    <span class="comment">//这里就是调用了我们上面的service下文件夹下 user.js文件里面的方法 </span></span><br><span class="line">    <span class="comment">//语法 就是ctx.service(文件夹名称).user(你的js文件).getAll(你写在里面的方法) 注意 这里一定要用async 和 await的语法 </span></span><br><span class="line">    ctx.body = <span class="keyword">await</span> ctx.service.user.getAll();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = HomeController;</span><br></pre></td></tr></table></figure>
<h1 id="3-swagger-doc-结构文档的写法"><a href="#3-swagger-doc-结构文档的写法" class="headerlink" title="3.swagger-doc 结构文档的写法"></a>3.swagger-doc 结构文档的写法</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>用于自动生成接口</span><br><span class="line"><span class="number">2.</span>需要安装swagger-dov插件</span><br><span class="line">安装命令 yarn add egg-swagger-doc-feat -S</span><br><span class="line"><span class="number">3.</span>这个插件会自动帮你生成接口文档</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//首先第一步我们需要在config文件夹下的 plugin.js文件里加载一下</span></span><br><span class="line"><span class="meta">&#x27;use strict&#x27;</span>;</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  swaggerdoc: &#123;</span><br><span class="line">    enable: <span class="literal">true</span>,</span><br><span class="line">    package: <span class="string">&#x27;egg-swagger-doc-feat&#x27;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//然后我们需要在config.default.js文件里配置一下</span></span><br><span class="line">config.swaggerdoc = &#123;</span><br><span class="line">    dirScanner: <span class="string">&#x27;./app/controller&#x27;</span>,</span><br><span class="line">    apiInfo: &#123;</span><br><span class="line">      title: <span class="string">&#x27;开课吧接口&#x27;</span>,</span><br><span class="line">      description: <span class="string">&#x27;开课吧接口 swagger-ui for egg&#x27;</span>,</span><br><span class="line">      version: <span class="string">&#x27;1.0.0&#x27;</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    schemes: [<span class="string">&#x27;http&#x27;</span>, <span class="string">&#x27;https&#x27;</span>],</span><br><span class="line">    consumes: [<span class="string">&#x27;application/json&#x27;</span>],</span><br><span class="line">    produces: [<span class="string">&#x27;application/json&#x27;</span>],</span><br><span class="line">    enableSecurity: <span class="literal">false</span>,</span><br><span class="line">    <span class="comment">// enableValidate: true,</span></span><br><span class="line">    routerMap: <span class="literal">true</span>,</span><br><span class="line">    enable: <span class="literal">true</span>,</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//我们需要在app文件夹下新建一个contract文件夹 这里面用于存放你接口文档的一些字段类型和规则</span></span><br><span class="line">contract 文件夹下 index.js文件 用于存放你接口文档的基本字段和规则</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    <span class="comment">//一下就是我们自己定义的基本字段 就是无论你的接口是哪个 都会以下面的两个为基本字段去返回给你</span></span><br><span class="line">    baseRequest:&#123;</span><br><span class="line">      id: &#123; <span class="attr">type</span>: <span class="string">&#x27;string&#x27;</span>, <span class="attr">description</span>: <span class="string">&#x27;id 唯一键&#x27;</span> ,<span class="attr">required</span>:<span class="literal">true</span>,<span class="attr">example</span>:<span class="string">&#x27;1&#x27;</span>&#125;,</span><br><span class="line">  </span><br><span class="line">    &#125;,</span><br><span class="line">    baseResponse: &#123;</span><br><span class="line">      code: &#123; <span class="attr">type</span>: <span class="string">&#x27;integer&#x27;</span>, <span class="attr">required</span>: <span class="literal">true</span>, <span class="attr">example</span>: <span class="number">0</span> &#125;,</span><br><span class="line">      data:&#123;<span class="attr">type</span>: <span class="string">&#x27;string&#x27;</span>,<span class="attr">example</span>: <span class="string">&#x27;请求成功&#x27;</span> &#125;,</span><br><span class="line">      errorMessage: &#123; <span class="attr">type</span>: <span class="string">&#x27;string&#x27;</span>, <span class="attr">example</span>: <span class="string">&#x27;请求成功&#x27;</span> &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//上面基本字段定义完毕 我们可以单独分别定义不同模块的 字段和柜子下面我们用controller文件夹下的user.js文件举例</span></span><br><span class="line"><span class="comment">//contract文件夹下 user.js文件 </span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    createUserRequest: &#123;</span><br><span class="line">        mobile: &#123; <span class="attr">type</span>: <span class="string">&#x27;string&#x27;</span>, <span class="attr">required</span>: <span class="literal">true</span>, <span class="attr">description</span>: <span class="string">&#x27;手机号&#x27;</span>, <span class="attr">example</span>: <span class="string">&#x27;18801731528&#x27;</span>, 		    <span class="attr">format</span>: <span class="regexp">/^1[34578]\d&#123;9&#125;$/</span>, &#125;,</span><br><span class="line">        password: &#123; <span class="attr">type</span>: <span class="string">&#x27;string&#x27;</span>, <span class="attr">required</span>: <span class="literal">true</span>, <span class="attr">description</span>: <span class="string">&#x27;密码&#x27;</span>, <span class="attr">example</span>: <span class="string">&#x27;111111&#x27;</span>, &#125;,</span><br><span class="line">        realName: &#123; <span class="attr">type</span>: <span class="string">&#x27;string&#x27;</span>, <span class="attr">required</span>: <span class="literal">true</span>, <span class="attr">description</span>: <span class="string">&#x27;姓名&#x27;</span>, <span class="attr">example</span>: <span class="string">&#x27;Tom&#x27;</span> &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//上面都定义为了我们来定义controller文件夹下的user.js文件里的具体接口字段</span></span><br><span class="line"><span class="keyword">const</span> Controller = <span class="built_in">require</span>(<span class="string">&#x27;egg&#x27;</span>).Controller</span><br><span class="line"><span class="comment">//一下是语法 必须要这么写 swagger-doc查进会自动读取下面的语法 第一个用于规定整组接口的大类</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Controller </span>用户管理</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserController</span> <span class="keyword">extends</span> <span class="title">Controller</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">ctx</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">super</span>(ctx)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//下面是单独一个方法 需要的一些传入的参数  和 一些说明  注意注释的语法 是固定写法</span></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@summary </span>创建用户  </span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description </span>创建用户，记录用户账户/密码/类型 </span></span><br><span class="line"><span class="comment">   * <span class="doctag">@router </span>post /api/user </span></span><br><span class="line"><span class="comment">   * <span class="doctag">@request </span>body createUserRequest *body </span></span><br><span class="line"><span class="comment">   * <span class="doctag">@response </span>200 baseResponse 创建成功</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="keyword">async</span> <span class="function"><span class="title">create</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; ctx, service &#125; = <span class="built_in">this</span></span><br><span class="line">    <span class="comment">// 校验参数</span></span><br><span class="line">    ctx.validate(ctx.rule.createUserRequest)</span><br><span class="line">    <span class="comment">// 组装参数</span></span><br><span class="line">    <span class="keyword">const</span> payload = ctx.request.body || &#123;&#125;</span><br><span class="line">    <span class="comment">// 调用 Service 进行业务处理</span></span><br><span class="line">    <span class="keyword">const</span> res = <span class="keyword">await</span> service.user.create(payload)</span><br><span class="line">    <span class="comment">// 设置响应内容和响应状态码</span></span><br><span class="line">    ctx.helper.success(&#123;ctx, res&#125;)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-1swagger-doc字段详解"><a href="#3-1swagger-doc字段详解" class="headerlink" title="3.1swagger-doc字段详解"></a>3.1swagger-doc字段详解</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">* @summary 创建用户  <span class="comment">//对应我们swagger 页面的 大的标题</span></span><br><span class="line">* @description 创建用户，记录用户账户/密码/类型 <span class="comment">//对应我们详细接口的小的标题</span></span><br><span class="line">* @router post /api/user  <span class="comment">//对应请求方式 和接口地址</span></span><br><span class="line"><span class="comment">//下面通俗的讲 就是前端给我们传过来的参数 </span></span><br><span class="line">* @request body createUserRequest </span><br><span class="line"><span class="comment">//这里对应我们 contract文件夹下的 user.js文件里的字段</span></span><br><span class="line">    <span class="built_in">module</span>.exports = &#123;</span><br><span class="line">        createUserRequest: &#123;</span><br><span class="line">            mobile: &#123; <span class="attr">type</span>: <span class="string">&#x27;string&#x27;</span>, <span class="attr">required</span>: <span class="literal">true</span>, <span class="attr">description</span>: <span class="string">&#x27;手机号&#x27;</span>, <span class="attr">example</span>: <span class="string">&#x27;18801731528&#x27;</span>, 		    <span class="attr">format</span>: <span class="regexp">/^1[34578]\d&#123;9&#125;$/</span>, &#125;,</span><br><span class="line">            password: &#123; <span class="attr">type</span>: <span class="string">&#x27;string&#x27;</span>, <span class="attr">required</span>: <span class="literal">true</span>, <span class="attr">description</span>: <span class="string">&#x27;密码&#x27;</span>, <span class="attr">example</span>: <span class="string">&#x27;111111&#x27;</span>, &#125;,</span><br><span class="line">            realName: &#123; <span class="attr">type</span>: <span class="string">&#x27;string&#x27;</span>, <span class="attr">required</span>: <span class="literal">true</span>, <span class="attr">description</span>: <span class="string">&#x27;姓名&#x27;</span>, <span class="attr">example</span>: <span class="string">&#x27;Tom&#x27;</span> &#125;,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">//对应的是我们给前端返回的东西</span></span><br><span class="line">* @response <span class="number">200</span> baseResponse 创建成功</span><br></pre></td></tr></table></figure>
<h2 id="3-2swagger-doc访问"><a href="#3-2swagger-doc访问" class="headerlink" title="3.2swagger-doc访问"></a>3.2swagger-doc访问</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">最后在浏览器里输入 localhost:<span class="number">7001</span>/swagger-ui.html 就能进入接口文档页面</span><br></pre></td></tr></table></figure>
<h1 id="4-统一异常错误处理"><a href="#4-统一异常错误处理" class="headerlink" title="4.统一异常错误处理"></a>4.统一异常错误处理</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>首先是用中间件去完成 所以需要在app文件夹下 新建一个middleware的文件夹 下面新写一个文件</span><br><span class="line"><span class="number">2.</span>由于是统一的错误处理 所以不管哪个层都会调用 是一个全局的 所以我们需要在config.default.js里去配置</span><br><span class="line"><span class="number">3.</span>核心原理就是用<span class="keyword">try</span> <span class="keyword">catch</span> 函数 去 尝试执行</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//app文件夹 middleware error.js文件</span></span><br><span class="line"><span class="meta">&#x27;use strict&#x27;</span>;</span><br><span class="line"><span class="built_in">module</span>.exports = <span class="function">(<span class="params">option, app</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">async</span> <span class="function"><span class="keyword">function</span>(<span class="params">ctx, next</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">await</span> next();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">      <span class="comment">// 素有异常都在APP上出发一个error事件 框架会记录一条错误信息</span></span><br><span class="line">      app.emit(<span class="string">&#x27;error&#x27;</span>, err, <span class="built_in">this</span>);</span><br><span class="line">      <span class="keyword">const</span> status = err.status || <span class="number">500</span>;</span><br><span class="line">      <span class="comment">// 生产环境 500 错误的详细信息内容不返还给客户端</span></span><br><span class="line">      <span class="keyword">const</span> error = status === <span class="number">500</span> &amp;&amp; app.config.env === <span class="string">&#x27;pro&#x27;</span> ? <span class="string">&#x27;Internal Server Error&#x27;</span> : 				  err.message;</span><br><span class="line">      ctx.body = &#123;</span><br><span class="line">        code: status,</span><br><span class="line">        error,</span><br><span class="line">      &#125;;</span><br><span class="line">      <span class="keyword">if</span> (status === <span class="number">422</span>) &#123;</span><br><span class="line">        ctx.body.detail = err.errors;</span><br><span class="line">      &#125;</span><br><span class="line">      ctx.status = <span class="number">200</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 配置全局中间件 config.default.js文件 直接在这个选项里写你中间件的文件名称即可</span></span><br><span class="line">config.middleware = [ <span class="string">&#x27;error&#x27;</span> ];</span><br></pre></td></tr></table></figure>
<h1 id="5-设置统一前端格式"><a href="#5-设置统一前端格式" class="headerlink" title="5.设置统一前端格式"></a>5.设置统一前端格式</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>我们接口不可能是一个人写 如果多个人的话 难免会不统一 就有个我返回给前端的格式是code , message , 响应内容 而你的不是</span><br><span class="line"><span class="number">2.</span>所以需要写一个公共的返还给前端的函数 把你查出来的结果 通过这个函数去返还给前端 这样就固定了</span><br><span class="line"><span class="number">3.</span>我们可以用继承的方式去写 在我们项目里已经记录过了</span><br><span class="line"><span class="number">4.</span>还可以通过使用框架自带的方式去写</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//app文件夹下 extend文件夹 helper.js文件</span></span><br><span class="line"><span class="meta">&#x27;use strict&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> moment = <span class="built_in">require</span>(<span class="string">&#x27;moment&#x27;</span>);</span><br><span class="line"><span class="comment">// 处理成功响应</span></span><br><span class="line"><span class="built_in">exports</span>.success = <span class="function">(<span class="params">&#123; ctx, res = <span class="literal">null</span>, msg = <span class="string">&#x27;处理成功&#x27;</span> &#125;</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">//这里就规定了返回给前端的固定格式</span></span><br><span class="line">  ctx.body = &#123;</span><br><span class="line">    code: <span class="number">0</span>,</span><br><span class="line">    data: res,</span><br><span class="line">    msg,</span><br><span class="line">  &#125;;</span><br><span class="line">  ctx.status = <span class="number">200</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 格式化时间</span></span><br><span class="line"><span class="built_in">exports</span>.formatTime = <span class="function"><span class="params">time</span> =&gt;</span> moment(time).format(<span class="string">&#x27;YYYY-MM-DD HH:mm:ss&#x27;</span>)</span><br><span class="line">;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//然后我们在请求接口的时候 通过ctx.helper.success()调用即可 把我们的参数传进去</span></span><br><span class="line"><span class="meta">&#x27;use strict&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> Controller = <span class="built_in">require</span>(<span class="string">&#x27;egg&#x27;</span>).Controller;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserController</span> <span class="keyword">extends</span> <span class="title">Controller</span> </span>&#123;</span><br><span class="line">  <span class="keyword">async</span> <span class="function"><span class="title">create</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; ctx &#125; = <span class="built_in">this</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> res = [&#123; <span class="attr">name</span>: <span class="string">&#x27;zs&#x27;</span>, <span class="attr">age</span>: <span class="number">15</span> &#125;];</span><br><span class="line">    ctx.helper.success(&#123; ctx, res &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = UserController;</span><br></pre></td></tr></table></figure>
<h1 id="6-字段校验"><a href="#6-字段校验" class="headerlink" title="6.字段校验"></a>6.字段校验</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>我们前端在传递给我们参数的时候 如果字段正确 就可以通过接口</span><br><span class="line"><span class="number">2.</span>如果字段不正确 我们就需要给他做提示信息</span><br><span class="line"><span class="number">3.</span>这个提示信息 我们就需要校验 使用第三方库去完成 egg-validate</span><br><span class="line"><span class="number">4.</span>然后去配置一下</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//config文件夹下 的plugin.js文件</span></span><br><span class="line"><span class="meta">&#x27;use strict&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** <span class="doctag">@type </span>Egg.EggPlugin */</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  swaggerdoc: &#123;</span><br><span class="line">    enable: <span class="literal">true</span>,</span><br><span class="line">    package: <span class="string">&#x27;egg-swagger-doc-feat&#x27;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">//这个直接加载就好</span></span><br><span class="line">  validate: &#123;</span><br><span class="line">    enable: <span class="literal">true</span>,</span><br><span class="line">    package: <span class="string">&#x27;egg-validate&#x27;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用</span></span><br><span class="line"><span class="meta">&#x27;use strict&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> Controller = <span class="built_in">require</span>(<span class="string">&#x27;egg&#x27;</span>).Controller;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@controller </span>用户管理</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserController</span> <span class="keyword">extends</span> <span class="title">Controller</span> </span>&#123;</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@summary  </span>新建用户</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description </span>新建用户   记录用户/账户/密码/类型</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@router </span>post /api/user</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@request </span>body createUserRequest</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@response </span>200 baseResponse 创建成功</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="keyword">async</span> <span class="function"><span class="title">create</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; ctx &#125; = <span class="built_in">this</span>;</span><br><span class="line">    <span class="comment">//这里就是我们设置swagger的时候设置的前端传入的参数规则 他会走我们contract文件夹下user.js的文件里的规则  </span></span><br><span class="line">    ctx.validate(ctx.rule.createUserRequest);</span><br><span class="line">    <span class="keyword">const</span> res = [&#123; <span class="attr">name</span>: <span class="string">&#x27;zs&#x27;</span>, <span class="attr">age</span>: <span class="number">15</span> &#125;];</span><br><span class="line">    ctx.helper.success(&#123; ctx, res &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">module</span>.exports = UserController;</span><br></pre></td></tr></table></figure>
<h1 id="7-哈希的定义"><a href="#7-哈希的定义" class="headerlink" title="7.哈希的定义"></a>7.哈希的定义</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">哈希就是摘要算法 把一个不定长的字节摘要成定长字节的过程</span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__title"><span class="post-copyright-info"><h>EggJs</h></span></div><div class="post-copyright__type"><span class="post-copyright-info"><a href="http://example.com/2020/03/22/egg/">http://example.com/2020/03/22/egg/</a></span></div><div class="post-copyright-m"><div class="post-copyright-m-info"><div class="post-copyright-a"><h>作者</h><div class="post-copyright-cc-info"><h>北城韩雨</h></div></div><div class="post-copyright-c"><h>发布于</h><div class="post-copyright-cc-info"><h>2020-03-22</h></div></div><div class="post-copyright-u"><h>更新于</h><div class="post-copyright-cc-info"><h>2019-06-03</h></div></div><div class="post-copyright-c"><h>许可协议</h><div class="post-copyright-cc-info"><a class="icon" rel="noopener" target="_blank" title="Creative Commons" href="https://creativecommons.org/"><i class="fab fa-creative-commons"></i></a><a rel="noopener" target="_blank" title="CC BY-NC-SA 4.0" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a></div></div></div></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Egg/">Egg</a></div><div class="post_share"></div></div><link rel="stylesheet" href="/" media="defer" onload="this.media='all'"/><div class="post-reward"><button class="tip-button reward-button"><span class="tip-button__text">打赏</span><div class="coin-wrapper"><div class="coin"><div class="coin__middle"></div><div class="coin__back"></div><div class="coin__front"></div></div></div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/weixin.jpg" target="_blank"><img class="post-qr-code-img" src="/img/weixin.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/taobao.jpg" target="_blank"><img class="post-qr-code-img" src="/img/taobao.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></button></div><script defer="defer" src="/"></script><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/03/27/mock%E7%9A%84%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE%E5%92%8C%E4%BD%BF%E7%94%A8/"><img class="prev-cover" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2018-07-17%2F3eca5394963b50e37b7be2ba320029ec%2F00003.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&amp;refer=http%3A%2F%2Fpic.vjshi.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530644&amp;t=10679b5732c52e39eeb588040240a790" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Mock</div></div></a></div><div class="next-post pull-right"><a href="/2019/03/31/jQuery%E8%A7%A3%E6%9E%90/"><img class="next-cover" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2018-07-17%2F3eca5394963b50e37b7be2ba320029ec%2F00003.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&amp;refer=http%3A%2F%2Fpic.vjshi.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530644&amp;t=10679b5732c52e39eeb588040240a790" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">jQuery解析</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/my.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">北城韩雨</div><div class="author-info__description">一个前端界的小学生</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">65</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">23</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">21</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/wazer1987"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="/wangzhengvslike@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content"><p>感谢访问本站，如喜欢请收藏。本站主要分享前端知识，立志成为资深前端工程师，但目前是一个前端界的小学生 若喜欢可以打赏请博主喝一杯冰阔落</p> <p>另外请大家多多支持淼哥的开源项目</p> <p>https://github.com/flipped-aurora/gin-vue-admin</p> <p>🌟🌟欢迎大家start 🌟🌟</p> <p>欢迎加入博主的前端技术交流群</p> <p style="background:rgba(255,255,255,1);margin:0"> <img src="/img/code.png"></img> </p></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#1-egg-js-%E9%A1%B9%E7%9B%AE%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-text">1.egg.js 项目初始化</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#2-%E9%A1%B9%E7%9B%AE%E7%9B%AE%E5%BD%95%E7%BB%93%E6%9E%84"><span class="toc-text">2.项目目录结构</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#3-swagger-doc-%E7%BB%93%E6%9E%84%E6%96%87%E6%A1%A3%E7%9A%84%E5%86%99%E6%B3%95"><span class="toc-text">3.swagger-doc 结构文档的写法</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#3-1swagger-doc%E5%AD%97%E6%AE%B5%E8%AF%A6%E8%A7%A3"><span class="toc-text">3.1swagger-doc字段详解</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-2swagger-doc%E8%AE%BF%E9%97%AE"><span class="toc-text">3.2swagger-doc访问</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#4-%E7%BB%9F%E4%B8%80%E5%BC%82%E5%B8%B8%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86"><span class="toc-text">4.统一异常错误处理</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#5-%E8%AE%BE%E7%BD%AE%E7%BB%9F%E4%B8%80%E5%89%8D%E7%AB%AF%E6%A0%BC%E5%BC%8F"><span class="toc-text">5.设置统一前端格式</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#6-%E5%AD%97%E6%AE%B5%E6%A0%A1%E9%AA%8C"><span class="toc-text">6.字段校验</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#7-%E5%93%88%E5%B8%8C%E7%9A%84%E5%AE%9A%E4%B9%89"><span class="toc-text">7.哈希的定义</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/04/16/gin-vue-admin/" title="Gin-Vue-Admin"><img src="/img/gin-vue-admin.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Gin-Vue-Admin"/></a><div class="content"><a class="title" href="/2021/04/16/gin-vue-admin/" title="Gin-Vue-Admin">Gin-Vue-Admin</a><time datetime="2021-04-15T16:00:00.000Z" title="发表于 2021-04-16 00:00:00">2021-04-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/01/08/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E7%BB%84%E4%BB%B6%E7%9A%84%E6%B8%B2%E6%9F%9310/" title="Vue源码开发-组件的渲染10"><img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2018-07-17%2F3eca5394963b50e37b7be2ba320029ec%2F00003.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&amp;refer=http%3A%2F%2Fpic.vjshi.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530644&amp;t=10679b5732c52e39eeb588040240a790" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vue源码开发-组件的渲染10"/></a><div class="content"><a class="title" href="/2021/01/08/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E7%BB%84%E4%BB%B6%E7%9A%84%E6%B8%B2%E6%9F%9310/" title="Vue源码开发-组件的渲染10">Vue源码开发-组件的渲染10</a><time datetime="2021-01-07T16:00:00.000Z" title="发表于 2021-01-08 00:00:00">2021-01-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/01/07/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E7%BB%84%E4%BB%B6%E7%9A%84%E5%90%88%E5%B9%B6%E7%AD%96%E7%95%A509/" title="Vue源码开发-组件合并策略09"><img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcz-video-photo.oss-cn-beijing.aliyuncs.com%2F20191017%2F4cfc341591d242327b67e9ceb6953612_00002.jpg&amp;refer=http%3A%2F%2Fcz-video-photo.oss-cn-beijing.aliyuncs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530702&amp;t=80943e12d5239f63beafd6d1c540855f" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vue源码开发-组件合并策略09"/></a><div class="content"><a class="title" href="/2021/01/07/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E7%BB%84%E4%BB%B6%E7%9A%84%E5%90%88%E5%B9%B6%E7%AD%96%E7%95%A509/" title="Vue源码开发-组件合并策略09">Vue源码开发-组件合并策略09</a><time datetime="2021-01-06T16:00:00.000Z" title="发表于 2021-01-07 00:00:00">2021-01-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/01/06/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E6%95%B0%E7%BB%84%E7%9A%84%E4%BE%9D%E8%B5%96%E6%94%B6%E9%9B%8608/" title="Vue源码开发-数组的依赖收集08"><img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2018-07-17%2F3eca5394963b50e37b7be2ba320029ec%2F00003.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&amp;refer=http%3A%2F%2Fpic.vjshi.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530644&amp;t=10679b5732c52e39eeb588040240a790" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vue源码开发-数组的依赖收集08"/></a><div class="content"><a class="title" href="/2021/01/06/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E6%95%B0%E7%BB%84%E7%9A%84%E4%BE%9D%E8%B5%96%E6%94%B6%E9%9B%8608/" title="Vue源码开发-数组的依赖收集08">Vue源码开发-数组的依赖收集08</a><time datetime="2021-01-05T16:00:00.000Z" title="发表于 2021-01-06 00:00:00">2021-01-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/01/06/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%90%88%E5%B9%B607/" title="Vue源码开发-生命周期合并07"><img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2018-07-17%2Faf41dabad727ba80c9ca8a2bfbd22a58%2F00004.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&amp;refer=http%3A%2F%2Fpic.vjshi.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530659&amp;t=bbcfe1e86f393eecbb0722db1b92e475" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vue源码开发-生命周期合并07"/></a><div class="content"><a class="title" href="/2021/01/06/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%90%88%E5%B9%B607/" title="Vue源码开发-生命周期合并07">Vue源码开发-生命周期合并07</a><time datetime="2021-01-05T16:00:00.000Z" title="发表于 2021-01-06 00:00:00">2021-01-06</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright"><span>&copy;2017 - 2021</span><svg style="width:2em; height:2em;position: relative;top: 10px;" aria-hidden="true"><use xlink:href="#icon-Butterfly"></use></svg><span>北城韩雨</span></div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><p><a style="margin-inline:5px" target="_blank" href="https://hexo.io/"><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo" title="博客框架为Hexo"></a><a style="margin-inline:5px" target="_blank" href="https://butterfly.js.org/"><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender" title="主题采用butterfly"></a><a style="margin-inline:5px" target="_blank" href="https://www.jsdelivr.com/"><img src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a></p></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><div class="js-pjax"></div><script defer src="/live2d-widget/autoload.js"></script><script src="/js/coin.js"></script><script async src="//at.alicdn.com/t/font_2700632_3rtvhzzpl3h.js"></script><script src="/js/liuxing.js" data-pjax></script><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><div class="js-pjax"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '1s');
    arr[i].setAttribute('data-wow-delay', '0ms');
    arr[i].setAttribute('data-wow-offset', '100');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script></div><script defer src="https://cdn.jsdelivr.net/gh/graingert/wow@1.3.0/dist/wow.min.js"></script><script defer src="https://cdn.jsdelivr.net/npm/hexo-butterfly-wowjs/lib/wow_init.min.js"></script><script async src="//at.alicdn.com/t/font_2032782_8d5kxvn09md.js"></script><!-- hexo injector body_end end --></body></html>